<template>
    <view class="container">
        <!-- 顶部状态栏 -->
        <view class="header">
            <view class="level-card">
                <text>第 {{ currentLevel }} 关</text>
                <view class="time-info">
                    <text class="game-time">用时：{{ formatTime(gameTime) }}</text>
                    <text class="remain-time">剩余：{{ timeLeft }}s</text>
                </view>
                <text class="restart-text" @click="resetGame">重新开始</text>
            </view>
        </view>
        <!-- 游戏区域卡片 -->
        <view class="game-card">
            <!-- 游戏网格 -->
            <view class="game-grid" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
                <view 
                    v-for="(block, index) in blocks" 
                    :key="index"
                    :class="['grid-block', !block.isEmpty ? 'active-block' : '']"
                    :style="{ 
                        top: block.position.row * 33.33 + '%',
                        left: block.position.col * 33.33 + '%'
                    }"
                >
                    <image 
                        v-if="!block.isEmpty" 
                        :src="block.imageUrl" 
                        class="block-image"
                    />
                </view>
            </view>
        </view>
        
        <!-- 添加自定义弹窗 -->
        <uni-popup ref="timeupPopup" type="center">
            <view class="custom-popup">
                <view class="popup-title">时间到！</view>
                <view class="popup-content">是否继续游戏？</view>
                <view class="popup-buttons">
                    <view class="popup-btn-item">
                        <view class="popup-btn continue-btn" @click="handleContinue">
                            <text class="btn-icon">▶</text>
                            <text>看广告继续</text>
                        </view>
                    </view>
                    <view class="popup-btn-item">
                        <view class="popup-btn share-btn" @click="handleContinue">
                            <text class="btn-icon">↗</text>
                            <text>转发到群复活</text>
                        </view>
                    </view>
                    <view class="popup-btn-item">
                        <view class="popup-btn end-btn" @click="handleEnd">结束</view>
                    </view>
                </view>
            </view>
        </uni-popup>
        
        <!-- 将一键拼图按钮移到这里，设置为悬浮按钮 -->
        <view class="float-debug-btn" @click="autoComplete">
            <text class="debug-icon">🧩</text>
        </view>
        
        <!-- 添加通关弹窗 -->
        <uni-popup ref="winPopup" type="center">
            <view class="custom-popup">
                <view class="popup-title">恭喜通关！</view>
                <view class="popup-content">你完成了第 {{ currentLevel }} 关！用时 {{ formatTime(gameTime) }}</view>
                <view class="popup-buttons">
                    <view class="popup-btn-item">
                        <view class="popup-btn continue-btn" @click="handleNextLevel">
                            <text class="btn-icon">▶</text>
                            <text>下一关</text>
                        </view>
                    </view>
                    <view class="popup-btn-item">
                        <view class="popup-btn download-btn" @click="handleDownload">
                            <text class="btn-icon">⬇</text>
                            <text>下载原图</text>
                        </view>
                    </view>
                    <view class="popup-btn-item">
                        <view class="popup-btn end-btn" @click="handleQuit">退出</view>
                    </view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>
<style>
.container {
    min-height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
    padding: 20rpx;
}
.header {
    padding: 20rpx;
}
.level-card {
    background-color: #fff;
    padding: 20rpx 30rpx;
    border-radius: 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}
.time {
    color: #4CAF50;
    font-weight: bold;
}
.game-card {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}
.game-grid {
    position: relative;
    width: 80vw;
    height: 80vw;
    max-width: 600rpx;
    max-height: 600rpx;
    background-color: #f8f8f8;
    border-radius: 10rpx;
    overflow: hidden;
    touch-action: none;
}
.grid-block {
    position: absolute;
    width: 32%;
    height: 32%;
    margin: 0.665%;
    border-radius: 10rpx;
    transition: all 0.15s ease-out;
    overflow: hidden;
}
.block-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: all 0.15s ease-out;
}
.active-block {
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
.grid-block:not(.active-block) {
    background-color: transparent;
    border: none;
    box-shadow: none;
}
.active-block:active {
    transform: scale(0.95);
}
.restart-text {
    font-size: 24rpx;
    color: #999;
    margin-left: 20rpx;
}
.restart-text:active {
    opacity: 0.7;
}
.control-area {
    display: none;
}
/* 添加自定义弹窗样式 */
.custom-popup {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    width: 560rpx;
}
.popup-title {
    font-size: 40rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20rpx;
    color: #333;
}
.popup-content {
    font-size: 32rpx;
    text-align: center;
    margin-bottom: 40rpx;
    color: #666;
}
.popup-buttons {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
}
.popup-btn-item {
    width: 100%;
}
.popup-btn {
    width: 100%;
    padding: 24rpx 0;
    border-radius: 40rpx;
    font-size: 32rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
}
.btn-icon {
    font-size: 28rpx;
}
.continue-btn {
    background-color: #4CAF50;
    color: white;
}
.share-btn {
    background-color: #2196F3;
    color: white;
}
.end-btn {
    background-color: #ff6b6b;
    color: white;
}
.confirm-btn {
    background-color: #4CAF50;
    color: white;
    width: 200rpx;
    text-align: center;
}
.popup-btn:active {
    opacity: 0.8;
    transform: scale(0.98);
}
/* 移除原来的调试按钮样式 */
.debug-btn {
    display: none;
}
/* 添加新的悬浮调试按钮样式 */
.float-debug-btn {
    position: fixed;
    right: 30rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 80rpx;
    height: 80rpx;
    background-color: rgba(76, 175, 80, 0.1);
    border: 1px solid #4CAF50;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    opacity: 0.6;
}
.debug-icon {
    font-size: 40rpx;
}
.float-debug-btn:active {
    opacity: 0.8;
    background-color: rgba(76, 175, 80, 0.2);
}
.time-info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}
.game-time {
    color: #4CAF50;
    font-weight: bold;
    font-size: 24rpx;
}
.remain-time {
    color: #ff6b6b;
    font-weight: bold;
    font-size: 24rpx;
    margin-top: 4rpx;
}
/* 当剩余时间少于5秒时添加闪烁画 */
@keyframes flash {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
}
.remain-time.warning {
    animation: flash 1s infinite;
}
/* 添加下载按钮样式 */
.download-btn {
    background-color: #2196F3;
    color: white;
}
</style>
<script>
export default {
    data() {
        return {
            currentLevel: 1,
            gameTime: 0,
            timeLeft: 5,
            isPlaying: false,
            timer: null,
            timeoutTimer: null,
            blocks: [],
            emptyPosition: 8,
            touchStartX: 0,
            touchStartY: 0,
            hasStarted: false,
            targetState: [  // 添加目标状态
                {row: 0, col: 0, value: 1},
                {row: 0, col: 1, value: 2},
                {row: 0, col: 2, value: 3},
                {row: 1, col: 0, value: 4},
                {row: 1, col: 1, value: 5},
                {row: 1, col: 2, value: 6},
                {row: 2, col: 0, value: 7},
                {row: 2, col: 1, value: 8},
                {row: 2, col: 2, value: null}
            ]
        }
    },
    created() {
        this.initializeImage()
        this.initializeBlocks()
    },
    methods: {
        initializeImage() {
            // 获取图片信息
            uni.getImageInfo({
                src: '/static/pingtu/sheep.png',
                success: (res) => {
                    this.imageWidth = res.width
                    this.imageHeight = res.height
                    this.blockSize = {
                        width: res.width / 3,
                        height: res.height / 3
                    }
                }
            })
        },
        initializeBlocks() {
            const positions = [
                {row: 0, col: 0}, {row: 0, col: 1}, {row: 0, col: 2},
                {row: 1, col: 0}, {row: 1, col: 1}, {row: 1, col: 2},
                {row: 2, col: 0}, {row: 2, col: 1}, {row: 2, col: 2}
            ]
            
            this.blocks = positions.map((position, index) => ({
                value: index === 8 ? null : index + 1,
                position: position,
                isEmpty: index === 8,
                imageUrl: index === 8 ? '' : `/static/pingtu/sheep_0${index + 1}.png`
            }))
            this.shuffleBlocks()
        },
        async shuffleBlocks() {
            const shuffle = async () => {
                // 增加打乱次数到50次，确保充分随机
                for(let i = 0; i < 50; i++) {
                    const directions = ['up', 'down', 'left', 'right']
                    const randomDirection = directions[Math.floor(Math.random() * directions.length)]
                    this.moveDirection(randomDirection)
                    await new Promise(resolve => setTimeout(resolve, 30))  // 稍微加快动画
                }
                
                // 如果打乱后无解，继续打乱直到有解
                while (!this.isSolvable(this.blocks)) {
                    // 再随机移动几次
                    for(let i = 0; i < 10; i++) {
                        const directions = ['up', 'down', 'left', 'right']
                        const randomDirection = directions[Math.floor(Math.random() * directions.length)]
                        this.moveDirection(randomDirection)
                        await new Promise(resolve => setTimeout(resolve, 30))
                    }
                }
            }
            
            await shuffle()
        },
        checkWin() {
            // 检查每个方块是否在正确位置
            for (let i = 0; i < this.blocks.length; i++) {
                const block = this.blocks[i]
                // 最后一个位置应该是空的
                if (i === 8) {
                    if (!block.isEmpty) return false
                    continue
                }
                // 检查其他位置
                if (block.isEmpty) return false
                // 检查值和位置是否匹配
                const expectedRow = Math.floor(i / 3)
                const expectedCol = i % 3
                if (block.position.row !== expectedRow || 
                    block.position.col !== expectedCol || 
                    block.value !== i + 1) {
                    return false
                }
            }
            return true
        },
        moveDirection(direction) {
            const emptyBlock = this.blocks.find(block => block.isEmpty)
            const emptyPos = emptyBlock.position
            let targetBlock = null
            
            switch(direction) {
                case 'down':
                    targetBlock = this.blocks.find(block => 
                        block.position.row === emptyPos.row - 1 && 
                        block.position.col === emptyPos.col
                    )
                    break
                case 'up':
                    targetBlock = this.blocks.find(block => 
                        block.position.row === emptyPos.row + 1 && 
                        block.position.col === emptyPos.col
                    )
                    break
                case 'right':
                    targetBlock = this.blocks.find(block => 
                        block.position.col === emptyPos.col - 1 && 
                        block.position.row === emptyPos.row
                    )
                    break
                case 'left':
                    targetBlock = this.blocks.find(block => 
                        block.position.col === emptyPos.col + 1 && 
                        block.position.row === emptyPos.row
                    )
                    break
            }
            
            if (targetBlock) {
                const targetIndex = this.blocks.indexOf(targetBlock)
                const emptyIndex = this.blocks.indexOf(emptyBlock)
                
                const newBlocks = this.blocks.map(block => ({...block}))
                
                // 将目标方块的值和图片移动到空位
                newBlocks[emptyIndex] = {
                    ...newBlocks[emptyIndex],
                    value: targetBlock.value,
                    isEmpty: false,
                    imageUrl: targetBlock.imageUrl
                }
                
                // 将原来的位置设置为空位
                newBlocks[targetIndex] = {
                    ...newBlocks[targetIndex],
                    value: null,
                    isEmpty: true,
                    imageUrl: ''
                }
                
                this.blocks = newBlocks
                this.emptyPosition = targetIndex
                
                // 只在游戏进行中检查胜利
                if (this.isPlaying && this.checkWin()) {
                    this.handleWin()
                }
            }
        },
        handleWin() {
            if (!this.isPlaying) return
            
            // 停止所有计时器
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
            if (this.timeoutTimer) {
                clearInterval(this.timeoutTimer)
                this.timeoutTimer = null
            }
            
            this.isPlaying = false

            // 显示自定义通关弹窗
            this.$refs.winPopup.open()
        },
        handleTouchStart(event) {
            this.touchStartX = event.touches[0].clientX
            this.touchStartY = event.touches[0].clientY
            
            if (!this.hasStarted) {
                this.hasStarted = true
                this.isPlaying = true
                this.gameTime = 0
                this.startTimer()
            }
        },
        handleTouchEnd(event) {
            if (!this.isPlaying) return
            const touchEndX = event.changedTouches[0].clientX
            const touchEndY = event.changedTouches[0].clientY
            
            const deltaX = touchEndX - this.touchStartX
            const deltaY = touchEndY - this.touchStartY
            
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                if (deltaX > 50) {
                    this.moveDirection('right')
                } else if (deltaX < -50) {
                    this.moveDirection('left')
                }
            } else {
                if (deltaY > 50) {
                    this.moveDirection('down')
                } else if (deltaY < -50) {
                    this.moveDirection('up')
                }
            }
        },
        resetGame() {
            if (!this.isPlaying) return
            
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
            if (this.timeoutTimer) {
                clearInterval(this.timeoutTimer)
                this.timeoutTimer = null
            }
            this.gameTime = 0
            this.timeLeft = 5
            this.hasStarted = false
            this.isPlaying = false
            this.initializeBlocks()
        },
        gameOver() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
            // 显示自定义弹窗
            this.$refs.timeupPopup.open()
        },
        handleContinue() {
            this.$refs.timeupPopup.close()
            this.timeLeft = 5
            this.isPlaying = true
            this.startTimer()
        },
        handleEnd() {
            this.$refs.timeupPopup.close()
            // 直接重置游戏状态，不显示确认弹窗
            this.resetGameState()
        },
        startTimer() {
            // 游戏时间计时器
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
            this.timer = setInterval(() => {
                this.gameTime++
            }, 1000)
            // 剩余时间计时器
            if (this.timeoutTimer) {
                clearInterval(this.timeoutTimer)
                this.timeoutTimer = null
            }
            this.timeoutTimer = setInterval(() => {
                if (this.timeLeft > 0) {
                    this.timeLeft--
                    // 当剩余时间小于等于5秒时，震动提示
                    if (this.timeLeft <= 5) {
                        uni.vibrateShort()
                    }
                } else {
                    this.gameOver()
                }
            }, 1000)
        },
        resetGameState() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
            if (this.timeoutTimer) {
                clearInterval(this.timeoutTimer)
                this.timeoutTimer = null
            }
            
            this.gameTime = 0
            this.timeLeft = 5
            this.currentLevel = 1
            this.hasStarted = false
            this.isPlaying = false
            
            this.initializeBlocks()
            setTimeout(async () => {
                await this.shuffleBlocks()
            }, 500)
        },
        getBackgroundPosition(position) {
            // 计算背景位置，使每个方块显示图片的对应部分
            const x = -(position.col * 100)
            const y = -(position.row * 100)
            return `${x}% ${y}%`
        },
        // 优化可解性检查方法
        isSolvable(blocks) {
            let inversions = 0
            const values = blocks
                .filter(block => !block.isEmpty)
                .map(block => block.value)
                .filter(value => value !== null)  // 确保只计算有效数字
            
            // 计算逆序数
            for (let i = 0; i < values.length - 1; i++) {
                for (let j = i + 1; j < values.length; j++) {
                    if (values[i] > values[j]) {
                        inversions++
                    }
                }
            }
            
            // 获取空格所在行数（从底部数）
            const emptyBlock = blocks.find(block => block.isEmpty)
            const emptyRow = 3 - emptyBlock.position.row
            
            // 在3x3的拼图中：
            // 当空格在最后一行时，逆序数必须为偶数
            // 当空格在倒数第二行时，逆序数必须为奇数
            // 当空格在第一行时，逆序数必须为偶数
            return (emptyRow % 2 === 0) === (inversions % 2 === 0)
        },
        // 添加一键拼图方法
        autoComplete() {
            // 直接将方块排列成正确顺序
            const positions = [
                {row: 0, col: 0}, {row: 0, col: 1}, {row: 0, col: 2},
                {row: 1, col: 0}, {row: 1, col: 1}, {row: 1, col: 2},
                {row: 2, col: 0}, {row: 2, col: 1}, {row: 2, col: 2}
            ]
            
            this.blocks = positions.map((position, index) => ({
                value: index === 8 ? null : index + 1,
                position: position,
                isEmpty: index === 8,
                imageUrl: index === 8 ? '' : `/static/pingtu/sheep_0${index + 1}.png`
            }))
            
            // 检查是否获胜
            if (this.checkWin()) {
                this.handleWin()
            }
        },
        // 添加时间格式化方法
        formatTime(seconds) {
            const minutes = Math.floor(seconds / 60)
            const remainingSeconds = seconds % 60
            return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
        },
        handleNextLevel() {
            this.$refs.winPopup.close()
            // 进入下一关
            this.currentLevel++
            this.gameTime = 0
            this.timeLeft = 5
            this.hasStarted = false
            this.isPlaying = false
            this.initializeBlocks()
        },
        handleQuit() {
            this.$refs.winPopup.close()
            // 返回上一页
            uni.navigateBack()
        },
        // 修改下载原图方法
        handleDownload() {
            // 获取当前页面路径
            const pages = getCurrentPages()
            const currentPage = pages[pages.length - 1]
            // 构建完整的图片路径
            const baseUrl = currentPage.$page.route.split('/').slice(0, -1).join('/')
            const imagePath = `/static/pingtu/sheep.png`

            uni.showLoading({
                title: '下载中...'
            })
            
            // 先复制本地图片
            uni.saveImageToPhotosAlbum({
                filePath: imagePath,
                success: () => {
                    uni.hideLoading()
                    uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                    })
                },
                fail: (err) => {
                    console.error('保存失败:', err)
                    // 如果本地保存失败，尝试网络下载
                    uni.downloadFile({
                        url: 'http://localhost:5173/static/pingtu/sheep.png',  // 替换为你的实际图片URL
                        success: (res) => {
                            if (res.statusCode === 200) {
                                uni.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePath,
                                    success: () => {
                                        uni.showToast({
                                            title: '保存成功',
                                            icon: 'success'
                                        })
                                    },
                                    fail: () => {
                                        uni.showToast({
                                            title: '保存失败',
                                            icon: 'error'
                                        })
                                    }
                                })
                            } else {
                                uni.showToast({
                                    title: '下载失败',
                                    icon: 'error'
                                })
                            }
                        },
                        fail: () => {
                            uni.showToast({
                                title: '下载失败',
                                icon: 'error'
                            })
                        }
                    })
                },
                complete: () => {
                    uni.hideLoading()
                }
            })
        }
    },
    onUnload() {
        if (this.timer) {
            clearInterval(this.timer)
        }
    }
}
</script>
